package com.pocketsweet.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.RefreshCallback;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.C;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLSignRecord;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.ActionSheetDialog;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.AutoListView.OnLoadListener;
import com.pocketsweet.ui.uilib.AutoListView.OnRefreshListener;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.ui.uilib.adapter.OnLineListAdapter;
import com.pocketsweet.ui.uilib.adapter.SignRecordAdapter;
import com.pocketsweet.utils.ToolKits;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@ContentView(R.layout.activity_sign_record)
public class SignInRecord extends BaseActivity implements OnRefreshListener,
        OnLoadListener, View.OnClickListener, AdapterView.OnItemClickListener {

    @ViewInject(R.id.signRecordListview)
    private AutoListView signRecordListview;

    @ViewInject(R.id.mainHeader)
    private HeaderLayout header;

    @ViewInject(R.id.tvSign)
    private TextView tvSign;

    public static LoadingDailog loading;
    private SignRecordAdapter signRecordAdapter;
    private List<MLSignRecord> mlSignRecords = new ArrayList<MLSignRecord>();
    private Context ctx;
    public static final int BEGIN_TO_LOADING = -1;
    private int skipDataCount = 0; // 忽略前N个对象
    public static final int MORE_DATA_MAX_COUNT = 10; // 每页10个对象
    private boolean isUpdateList = false; // 是否刷新列表
    private boolean isNowCanSignIn = false;
    private boolean isTodayHasSignInChance = false;
    ActionSheetDialog dialog = null;//这里先设置为null

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        ctx = this;
        signRecordAdapter = new SignRecordAdapter(SignInRecord.this,
                mlSignRecords);
        signRecordListview.setAdapter(signRecordAdapter);
        signRecordListview.setPageSize(MORE_DATA_MAX_COUNT);
        signRecordListview.setOnRefreshListener(this);
        signRecordListview.setOnLoadListener(this);
        signRecordListview.setOnItemClickListener(this);
        setHeaderFunction();
        getRecordList(AutoListView.REFRESH);
        tvSign.setOnClickListener(this);
    }

    public void setHeaderFunction() {
        header = (HeaderLayout) findViewById(R.id.mainHeader);
        header.init(HeaderStyle.IMG_TITLE_TEXT);
        header.setRightText("");
        header.setMiddleText("晚睡打卡");
        header.setLeftContainerClickListener(new onLeftContainerListener() {

            @Override
            public void onClick() {
                SignInRecord.this.finish();
            }
        });
    }

    private void getRecordList(final int what) {
        if (what != BEGIN_TO_LOADING) {
            isUpdateList = true; // 如果不是首次加载数据，则该动作为刷新
        } else {
            signRecordListview.setRefreshData(); // 初始化显示loading动态图片
        }
        if (mlSignRecords == null || mlSignRecords.size() <= 0
                || isUpdateList) { // userList为空或者动作为下拉刷新、往下加载时请求leanCloud

            AVQuery<MLSignRecord> querys = new AVQuery<MLSignRecord>("MLSignRecord");
            skipDataCount = skipDataCount + MORE_DATA_MAX_COUNT; // 往下加载时忽略前一页
            if (what != AutoListView.LOAD) {
                skipDataCount = 0; // 刷新时不用忽略前面对象
            }
            querys.orderByDescending("createdAt");
            querys.include("user");
            querys.setSkip(skipDataCount); // 忽略前N个
            querys.limit(MORE_DATA_MAX_COUNT); // 设置每页对象个数
            querys.findInBackground(new FindCallback<MLSignRecord>() {

                @Override
                public void done(List<MLSignRecord> records, AVException e) {
                    if (e == null) {
                        if (records.size() > 0) {
                            switch (what) {
                                case AutoListView.REFRESH: // 下拉刷新时直接重新获取数据
                                    mlSignRecords = records;
                                    signRecordListview.onRefreshComplete();
                                    // onLineListAdapter.setDatas(userList);
                                    break;
                                case AutoListView.LOAD: // 加载更多时把新获取的数据添加到list列表
                                    signRecordListview.onLoadComplete();
                                    mlSignRecords.addAll(records);
                                    break;
                                case BEGIN_TO_LOADING: // Application无数据时首次加载，即重新获取数据
                                    mlSignRecords = records;
                                    signRecordListview.onRefreshComplete();
                                    // onLineListAdapter.setDatas(userList);
                                    break;
                            }
                            signRecordListview.setResultSize(mlSignRecords
                                    .size());
                            signRecordAdapter.setDatas(mlSignRecords);
                            signRecordAdapter.notifyDataSetChanged();
                            isUpdateList = false; // 刷新完毕，设为false
                        } else if (records.size() == 0) {
                            if (what != AutoListView.LOAD) {
                                ToolKits.toast(SignInRecord.this, "没有打卡记录");
                            }
                            signRecordListview.setNoData();
                        }
                    } else {
                        // 已加载完全部，取消loading
//						Log.e("====mlFriendApplies", "nothing" + e.getMessage());
                        getRecordList(BEGIN_TO_LOADING);

                    }
                }

            });
        }
    }

    @Override
    public void onLoad() {
        getRecordList(AutoListView.LOAD);

    }

    @Override
    public void onRefresh() {
        getRecordList(AutoListView.REFRESH);
        signRecordListview.setOnRefreshListener(this);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    private void sign() {
        if (dialog != null && dialog.getIsShow() == true) {
            dialog.dismiss();
        } else {
            dialog = new ActionSheetDialog(SignInRecord.this);
            dialog.builder()
                    .setCancelable(true)
                    .setCanceledOnTouchOutside(true)
                    .addSheetItem("无聊中", ActionSheetDialog.SheetItemColor.Gray,
                            new ActionSheetDialog.OnSheetItemClickListener() {
                                @Override
                                public void onClick(int which) {
                                    saveSignRecord("无聊中");
                                }
                            })
                    .addSheetItem("加班中", ActionSheetDialog.SheetItemColor.Gray,
                            new ActionSheetDialog.OnSheetItemClickListener() {
                                @Override
                                public void onClick(int which) {
                                    saveSignRecord("加班中");
                                }
                            })
                    .addSheetItem("想听你唱歌", ActionSheetDialog.SheetItemColor.Gray,
                            new ActionSheetDialog.OnSheetItemClickListener() {
                                @Override
                                public void onClick(int which) {
                                    saveSignRecord("想听你唱歌");
                                }
                            })
                    .addSheetItem("困困哒", ActionSheetDialog.SheetItemColor.Gray,
                            new ActionSheetDialog.OnSheetItemClickListener() {
                                @Override
                                public void onClick(int which) {
                                    saveSignRecord("困困哒");
                                }
                            })
                    .addSheetItem("晚安", ActionSheetDialog.SheetItemColor.Gray,
                            new ActionSheetDialog.OnSheetItemClickListener() {
                                @Override
                                public void onClick(int which) {
                                    saveSignRecord("晚安");
                                }
                            });
            dialog.show();
        }
    }

    int randomMoney = 0;

    //保存打卡纪录到MLSignRecord表上
    private void saveSignRecord(final String mood) {
        int randomIn100 = (int) (Math.random() * 100);
        if (randomIn100 <= 50) {
            randomMoney = 1;
        } else if (randomIn100 <= 80) {
            randomMoney = 2;
        } else if (randomIn100 <= 95) {
            randomMoney = 3;
        } else if (randomIn100 <= 99) {
            randomMoney = 4;
        } else if (randomIn100 == 100) {
            randomMoney = 5;
        }
//        final int random = (int) (Math.random() * 10) % 4 + 1;// 1~5随机数
        tvSign.setClickable(false);
        MLSignRecord mlSignRecord = new MLSignRecord();
        MLUser mlUser = new MLUser();
        mlUser.setObjectId(UserService.getCurrentUserId());
        mlSignRecord.setUser(mlUser);
        mlSignRecord.setMood(mood);
        mlSignRecord.setMoney(randomMoney);
        mlSignRecord.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    UserService.getCurrentUser().refreshInBackground(new RefreshCallback<AVObject>() {
                        @Override
                        public void done(AVObject avObject, AVException e) {
                            tvSign.setClickable(true);
                            if (e == null) {
                                isTodayHasSignInChance = false;
                                MLUser currentUser = UserService.getCurrentUser();
//                                final int random = (int) (Math.random() * 10) % 4 + 1;// 1~5随机数
                                double balance = currentUser.getBalance();
                                double randomSign = (float) randomMoney / 10;
                                balance = balance + randomSign;
                                currentUser.increment("signCount");
                                BigDecimal balanceFormat = new BigDecimal(
                                        balance)
                                        .setScale(
                                                2,
                                                BigDecimal.ROUND_HALF_UP);
                                balance = balanceFormat
                                        .doubleValue();
                                currentUser.setBalance(balance);
                                currentUser.saveInBackground(new SaveCallback() {
                                                                 @Override
                                                                 public void done(AVException e) {
                                                                     if (e == null) {
                                                                         final MyAlertDialog dialog = new MyAlertDialog(
                                                                                 SignInRecord.this).builder()
                                                                                 .setTitleImg(R.drawable.sign_in_succeed)
                                                                                 .setMsg("+" + String.valueOf(randomMoney) + "时光")
                                                                                 .setPositiveButton("知道了", new View.OnClickListener() {
                                                                                     @Override
                                                                                     public void onClick(View v) {
                                                                                     }
                                                                                 });
                                                                         dialog.show();
                                                                     } else {
                                                                         ToolKits.toast(SignInRecord.this, "打卡失败");

                                                                     }
                                                                 }
                                                             }
                                );
                            }
                        }
                    });
                } else {
                    ToolKits.toast(SignInRecord.this, "打卡失败");
                    tvSign.setClickable(true);
                }
            }
        });

    }

    //初始化今日是否可以打卡
    private void canSignIn() {
        loading = ToolKits.createLoadingDialog(SignInRecord.this, "正在获取中");
        loading.show();
        tvSign.setClickable(false);
        AVQuery<MLSignRecord> querys = new AVQuery<MLSignRecord>("MLSignRecord");
        querys.orderByDescending("createdAt");
        querys.whereEqualTo("user", UserService.getCurrentUser());
        querys.findInBackground(new FindCallback<MLSignRecord>() {
            @Override
            public void done(final List<MLSignRecord> list, AVException e) {
                if (e == null) {
                    AVCloud.callFunctionInBackground("getNetTime", null,
                            new FunctionCallback<Long>() {

                                @Override
                                public void done(Long time, AVException e) {
                                    if (loading.isShowing()) {
                                        loading.dismiss();
                                    }
                                    if (e == null) {
                                        if (list.size() > 0) {
                                            final MLSignRecord mlSignRecord = list.get(0);
                                            Date currentDate = new Date(time);
                                            Date lastDate = mlSignRecord.getCreatedAt();
                                            long diff = 0;
                                            diff = currentDate.getTime() - lastDate.getTime();// 计算今日是否可以打卡
                                            if (diff > 72000000) {// 20 * 60 * 60 * 1000=18000000 毫秒
                                                isTodayHasSignInChance = true;
                                            } else {
                                                isTodayHasSignInChance = false;
                                            }
                                        } else {
                                            isTodayHasSignInChance = true;
                                        }
                                        isNowCanSignIn = ToolKits.canSignIn(time);// 计算现在是否为打卡时段
                                        if (isNowCanSignIn == false) {
                                            final MyAlertDialog dialog = new MyAlertDialog(
                                                    SignInRecord.this).builder()
                                                    .setTitleImg(R.drawable.sign_in_failure)
                                                    .setMsg("每天打卡时间：晚上10点到凌晨1点")
                                                    .setPositiveButton("知道了", new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View v) {
                                                        }
                                                    });
                                            dialog.show();
                                        } else if (isNowCanSignIn == true && isTodayHasSignInChance == true) {
                                            sign();
                                        } else if (isNowCanSignIn == true && isTodayHasSignInChance == false) {
                                            final MyAlertDialog dialog = new MyAlertDialog(
                                                    SignInRecord.this).builder()
                                                    .setMsg("今天已打")
                                                    .setPositiveButton("知道了", new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View v) {
                                                        }
                                                    });
                                            dialog.show();
                                        }
                                        tvSign.setClickable(true);
                                    } else {
                                        tvSign.setClickable(true);
                                        ToolKits.toast(SignInRecord.this, "获取时间失败");
                                    }

                                }
                            }

                    );
                } else {
                    ToolKits.toast(SignInRecord.this, "网络错误");
                    tvSign.setClickable(true);
                    if (loading.isShowing()) {
                        loading.dismiss();
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvSign:
                canSignIn();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        if (position - 1 < 0 || signRecordAdapter.getCount() <= 0) {
            return;
        }
        MLSignRecord mlSignRecord = (MLSignRecord) signRecordAdapter.getItem(position - 1);
        MLUser mlUser = mlSignRecord.getUser();
        String selectedUserId = mlUser.getObjectId();
        Intent intent;
        intent = new Intent(SignInRecord.this, Profile.class);
        intent.putExtra("userId", selectedUserId);
        intent.putExtra("nickname", mlUser.getNickname());
        startActivity(intent);

        // }

    }
}
